package pl.edu.agh.iosr.gamblingzone.action;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.richfaces.model.TreeNode;

import java.util.Iterator;
import java.util.List;

import pl.edu.agh.iosr.gamblingzone.dao.DisciplineDAO;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.DisciplineDAOBean;
import pl.edu.agh.iosr.gamblingzone.model.Discipline;
import pl.edu.agh.iosr.gamblingzone.model.Group;

@Stateless
@Name("treebean")
//@Scope(ScopeType.SESSION)

public class GroupsTreeAction implements GroupsTree {
	@PersistenceContext
	protected EntityManager entityManager;
	
	//@Out
	private TreeNode tree;

	private DisciplineDAO disciplineDAO;
	private List<Discipline> allDisciplines;

	private void setupDAO() {
        if (disciplineDAO == null) {
                disciplineDAO = new DisciplineDAOBean();
                ((DisciplineDAOBean) disciplineDAO).setEntityManager(entityManager);
        }
	}

	private List<Discipline> getAllDisciplines() {
        setupDAO();
        allDisciplines = disciplineDAO.findAll();
        return allDisciplines;
	}

	//@Create
	private void createTree() {
		tree = new GroupsTreeNodeImpl();
		List<Discipline> discs = getAllDisciplines();
		int counter=1;
		for(Iterator<Discipline> iterDisc = discs.iterator(); iterDisc.hasNext(); )
		{
			Discipline disc = iterDisc.next();
			GroupsTreeNodeImpl tmpNode = new GroupsTreeNodeImpl();
			tmpNode.setData(disc.getName());
			int grpCounter = 1;
			for(Iterator<Group>iterGrp = disc.getGroups().iterator(); iterGrp.hasNext(); )
			{
				Group grp = iterGrp.next();
				GroupsTreeNodeImpl tmpGrpNode = new GroupsTreeNodeImpl();
				tmpGrpNode.setData(grp.getName());
				tmpNode.addChild(grpCounter++, tmpGrpNode);
			}
			tree.addChild(counter++, tmpNode);
		}
	}
	
	@Out
	public TreeNode getTree() {
		createTree();
		return tree;
	}

	public void setTree(TreeNode tree) {
		this.tree = tree;
	}
}
